import { Options, DEFAULT, Scroll, Column } from "./type"
import { debounce, getValueByModel, isChinese, isEnglish } from "./util";
import FarmentCanvas from "./fargment";

export default class CanvasTable {
    root?: HTMLElement;
    options?: Options;
    Farment?: any[] = [];
    scroll?: Scroll;
    columnsWidths: number[] = []

    resizeHandel?: any
    resizeTimer: any;
    drawTimer: any;
    constructor (root: HTMLElement, options: Options){
        this.root = root;
        this.options = Object.assign({ fontSize: 12 }, options);
        this.scroll = Object.assign({ scrollTop: 0 }, options.scroll)

        this.init()
    }

    /**
     * 初始化 以及渲染
     */
    init(){
        this.resizeHandel = debounce(() => {
            clearTimeout(this.resizeTimer)
            this.resizeTimer = null;
            this.resizeTimer = setTimeout(() => {
                this.Farment?.forEach(f => {
                    f.canvas.remove()
                    f = null;
                });
                this.Farment = [];
                this.drawTable()
            }, 300)
        }, 500)

        this.drawTable()
    }

    /**
     * 销毁
     */
    destory(){
        this.Farment?.forEach(f => {
            f.canvas.remove()
            f = null;
        });
        this.Farment = [];
        window.removeEventListener('resize', this.resizeHandel)
    }
    /**
     * 绘制表格数据
     */
    drawTable(){

        let farmentIndex = 0;
        let columnsWidths: number[] | null = null
        const draw = (dataSource: any[]) => {
            // 数据分片渲染
            const farmentLength = 50
            if (dataSource.length > farmentLength) {
                draw(dataSource.slice(0, farmentLength))
                this.drawTimer = setTimeout(() => {
                    farmentIndex++;
                    draw(dataSource.slice(farmentLength))
                }, 300)
                return;
            } else {
                const Farment = new FarmentCanvas(this.root!, {
                    ...this.options!,
                    dataSource: []
                })

                if (columnsWidths) {
                    Farment.columnsWidths = columnsWidths
                    Farment.draw(dataSource, { drawHead: false })
                } else {
                    Farment.draw(dataSource, { drawHead: true })
                    columnsWidths = Farment.columnsWidths;
                }

                this.Farment?.push(Farment!)
            }
        }

        clearTimeout(this.drawTimer)
        draw(this.options?.dataSource!)

        window.removeEventListener('resize', this.resizeHandel)
        window.addEventListener('resize', this.resizeHandel)
        
    }
}
